﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;

namespace JQuery
{
    public static partial class Extensions
    {
        internal static List<T> ByInterface<T>(this ControlCollection collection)
            where T: class
        {
            var _collection = new List<T>();

            foreach (Control Ctrl in collection)
            {
                if (Ctrl.IsTypeOf<T>())
                {
                    _collection.Add(Ctrl as T);
                }
                if (Ctrl.HasControls() == true)
                {
                    _collection.AddRange(Ctrl.Controls.ByInterface<T>());
                }
            }

            return _collection;
        }

        internal static bool IsTypeOf<T>(this Control ctrl)
            where T: class
        {
            return (ctrl.GetType().GetInterface(typeof(T).Name) != null);
        }

        public static TResult IsNotNull<T, TResult>(this T Obj, Func<T, TResult> func)
            where TResult: class
        {
            if (Obj != null)
                return func(Obj);
            else return null;
        }

        public static TResult IsNotNull<T, TResult>(this T Obj, TResult @default, Func<T, TResult> func)
        {
            if (Obj != null)
                return func(Obj);
            else return @default;
        }

        public static void IsNotNull<T>(this T Obj, Action<T> action)
        {
            if (Obj != null) action(Obj);
        }
    }
}
